package DAO;

import java.sql.ResultSet;
import java.sql.Statement;

import javax.swing.JOptionPane;

import Main.DBMain;
import View.AdminFrame;
import View.LoginFrame;
import View.QueryFrame;
import View.TeaFrame;

public class LoginDAO {
	private int rs_Type = 0;
	String sql = "";
	String pwd = "";
	int colNum;
	public LoginDAO(String role, String user, String password) throws Exception {
		/*连接数据库*/
		java.sql.Connection conn = DBMain.getConnection();
		Statement stmt = conn.createStatement();
		colNum=AddStudent.getCol();
		try {
			/*学生登录比对*/
			if ("学生".equals(role)) {
				sql = "select * from stu_info where stuNo='" + user + "' and stuPwd = '" + password + "'";
				ResultSet rs = stmt.executeQuery(sql);
				if (rs.next()) {
					pwd = rs.getString(colNum);
					rs_Type = 1;
				}
			} 
			/*/*教室登录比对*/
			else if ("教师".equals(role)) {
				sql = "select * from tea_info where teaName='" + user + "' and teaPwd = '" + password + "'";
				ResultSet rs = stmt.executeQuery(sql);
				if (rs.next()) {
					pwd = rs.getString(3);
					rs_Type = 2;
				}
			}
			/*管理员登录比对*/
			else if ("管理员".equals(role)) {
				sql = "select * from admin1 where Name1='" + user + "' and Pwd = '" + password + "'";
				ResultSet rs = stmt.executeQuery(sql);
				if (rs.next()) {
					pwd = rs.getString(2);
					rs_Type = 3;
				}
			}
			/*学生登录条件判断*/
			if ("学生".equals(role) && password.equals(pwd) && rs_Type == 1) {
				new QueryFrame();
			} 
			/*教师登录条件判断*/
			else if ("教师".equals(role) && password.equals(pwd) && rs_Type == 2) {
				new TeaFrame(user);
			}
			/*管理员登录条件判断*/
			else if("管理员".equals(role) && password.equals(pwd) && rs_Type == 3) {
				new AdminFrame();
			}
			/*登录失败*/
			else {
				JOptionPane.showMessageDialog(null, "登录失败，原因：用户和用户类型不匹配或者密码错误！");
				new LoginFrame();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
